<?php defined('BASEPATH') || exit('No direct script access allowed');

/**
 * Home controller
 */
use EasyWeChat\Foundation\Application;

class Home extends Front_Controller
{
    private $init_num = 0;//16520;
    private $_listURL = "/fang/";
    private $_sessionUserKey = 'wechat_user_test';
    private $_urlMiddle = 'topictest';
    /**
     * Constructor
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        
        $this->load->model('area/area_model');
        $this->load->model('news/news_model');
        //$this->load->model('tags/tags_model');
        $this->load->model('news/newstag_model');

        // $this->auth->restrict($this->permissionView);
        // $this->load->model('buildings/buildings_model');
        // $this->load->model('buildings/buildingshuxing_model');
        // $this->load->model('buildings/photos_model');
        // $this->load->model('area/area_model');
        // $this->load->model('vendor/vendor_model');
        // $this->load->model('category/category_model');
        // $this->lang->load('buildings');
        
        // $this->form_validation->set_error_delimiters("<span class='error'>", "</span>");
        
        // Template::set_block('sub_nav', 'building/_sub_nav');

        // Assets::add_module_js('buildings', 'huxing.js');
        // Assets::add_css(array('plugins/select2/select2.min.css', 'plugins/iCheck/all.css', 'plugins/datepicker/datepicker3.css'));
        // Assets::add_js(array(Template::theme_url('plugins/select2/select2.full.min.js'), 
        //                     Template::theme_url('plugins/iCheck/icheck.min.js'), 
        //                     Template::theme_url('plugins/datepicker/bootstrap-datepicker.js'), 
        //                     Template::theme_url('js/plupload-2.1.1/plupload.full.min.js'),
        //                     Template::theme_url('js/plupload-2.1.1/i18n/zh_CN.js'), 
        //                     Template::theme_url('js/qiniu.js')
        //                     ));
    }

    /**
     * Display a list of Buildings data.
     *
     * @return void
     */
    public function index($city = '', $tmpA = 0)
    {
        // 加载模型
        $this->load->model('hometop/hometop_model');
        $this->load->model('buildings/buildingstag_model');
        $this->load->model('buildings/buildings_model');
        $this->load->model('buildings/photos_model');
        $this->load->model('tags/tags_model');
        $this->load->library('user_agent');
        $this->load->driver('cache');
        $data['start'] = $start = 0;
        $data['offset'] = $offset = is_fang90_server_name() ? 20 : 8;
        //获取已启用的分类
        $tagswhere = array(
            'is_category'=>1,
            'status'=>1
            );
        $tags = $this->tags_model->find_all_by($tagswhere);
        $data['tags'] = $tags;
        //根据板块获取所有已开通的城市
        $citiestmp = $this->area_model->where('active=1 and deleted=0')->find_all();
        foreach ($citiestmp as $key => $value) {
            $cities[area_block_name()[$value->plates]][] = $value;
        }
        $data['cities'] = $cities;
        //获取目标城市,有目标城市则读取该城市的精选楼盘
        $city_code = isset($city) ?trim($city):'';
        $buildings = [];
        if($city_code){
            $citywhere = array(
                'code'=>$city_code,
                'active'=>1,
                'deleted'=>0
                );
            $city = $this->area_model->find_by($citywhere);
            if($city){
                $data['city'] = $city;
                //获取首页轮播图
                $homotop['pc'] = $this->hometop_model->where("(city = '$city->area_id' or city=1) and deleted = 0 and imgtype=1 ")->find_all();
                $homotop['mobile'] =  $this->hometop_model->where("(city = '$city->area_id' or city=1) and deleted = 0 and imgtype=2 ")->find_all();
                $data['homotop'] = $homotop;
                // 读取精选楼盘（tag_id = 2）的数据（type  1普通标签 2特色标签 3分类标签 4楼盘类型(住宅|别墅) 5装修情况）
                $targetBuildingIds = $this->buildingstag_model->where("tag_id = 2 and type = 3")->order_by('building_id', 'DESC')->find_all();
                if($targetBuildingIds){
                    foreach ($targetBuildingIds as $key => $value) {
                        $tmp = $this->buildings_model->where("deleted = 0 and city_id = '$city->area_id' ")->find($value->building_id);
                        if(!empty($tmp)){
                            $citywhere = array(
                                'area_id'=>$tmp->city_id
                            );
                            $city = $this->area_model->find_by($citywhere);
                            $tmp->city_code = $city->code;
                            $tmp->photo = $this->photos_model->getCoverPhotoByBuildingId($value->building_id);
//                          $tmp->brower = $this->cache->redis->get("brower_index_".$value->building_id)+$this->init_num;
                            $tmp->tags = $this->buildingstag_model->tags($value->building_id);
                             $buildings[] = $tmp;
                        }
                    }
                }
            }
        }else{ 
            //获取全局首页轮播图（默认轮播图）
            $homotop['pc'] = $this->hometop_model->where("(city = '321' or city=1) and deleted = 0 and imgtype=1 ")->find_all();
            $homotop['mobile'] =  $this->hometop_model->where("(city = '321' or city=1) and deleted = 0 and imgtype=2 ")->find_all();
            $data['homotop'] = $homotop;
            // 读取所有精选楼盘（tag_id = 2）的数据（type  1普通标签 2特色标签 3分类标签 4楼盘类型(住宅|别墅) 5装修情况）
            $targetBuildingIds = $this->buildingstag_model->limit($offset,$start)->where("tag_id = 2 and type = 3")->order_by('building_id', 'DESC')->find_all();
            if($targetBuildingIds){
                foreach ($targetBuildingIds as $key => $value) {
                    $tmp = $this->buildings_model->where("deleted = 0 ")->find($value->building_id);
                    if(!empty($tmp)){
                        $citywhere = array(
                            'area_id'=>$tmp->city_id
                        );
                        $city = $this->area_model->find_by($citywhere);
                        $tmp->city_code = $city->code;
                        $tmp->photo = $this->photos_model->getCoverPhotoByBuildingId($value->building_id);
//                      $tmp->brower = $this->cache->redis->get("brower_index_".$value->building_id)+$this->init_num;
                        $tmp->tags = $this->buildingstag_model->tags($value->building_id);
                        $buildings[] = $tmp;
                    }
                }
            
            }
         }
         $data['buildings'] = $buildings;
         //dump($data['buildings']);exit();
        $data['buildingsNum'] = count($buildings);
        $data['offset'] =  $offset;     
        //旧网站数据
        //$oldBuilding = $this->getConf('config');
        //$data['oldBuilding'] = $oldBuilding;
        //合并数据
        //$data['buildings'] = array_merge($buildings,$oldBuilding);
        //dump($data['buildings']);exit();
        $data['is_mobile'] = $this->agent->is_mobile();
        $data['tmp_a'] = $tmpA;
        $data['city_code'] = $city_code ? : 'shanghai';
        //dump($data);exit();
        //楼盘动态
        // $new_records = $this->news_model->find_all();
        // if($new_records){
        //     foreach ($new_records as $key => $value) {
        //         $new_records[$key]->tags = $this->newstag_model->tags($value->id);
        //         //获取分类
        //         if(isset($new_records[$key]->tags['tese'])){
        //             $newcategory="";
        //             foreach ($new_records[$key]->tags['tese'] as $fkey => $fvalue) {
                        
        //                     $newcategory .= $fvalue->tag_name."、";
        //                 }
        //                     $str_category = substr($newcategory, 0, -3);
        //                     $new_records[$key]->fenlei = $str_category;
        //             }else{
        //                 $new_records[$key]->fenlei = "无";
        //             }
        //         //获取标签
        //         if(isset($new_records[$key]->tags['putong'])){
        //             $newtag="";
        //             foreach ($new_records[$key]->tags['putong'] as $tkey => $tvalue) {                       
        //                     $newtag .= $tvalue->tag_name."、";
        //                 }
        //                     $str_tag = substr($newtag, 0, -3);
        //                     $new_records[$key]->tags = $str_tag;
        //             }else{
        //                 $new_records[$key]->tags = "无";
        //             }
        //         //口语化时间
        //         $new_records[$key]->ptime = $this->getTime($new_records[$key]->ctime); 
        //         // 城市参数
        //         $city_id = !empty($value->city)?$value->city:"321";
        //         $new_records[$key]->citycode = $this->area_model->find($city_id);
        //     }
        // }
        // $data['new_records'] = $new_records;
        //dump($data['new_records']);exit();
        $this->load->view('front/home/index', $data);
    }
    /**
     * [fangPlus 首页]
     * @author [fengchen@usuretech.com]
     * @DateTime 2017-02-10T10:02:59+0800
     * @return   [type]                   [description]
     */
    public function fangPlus(){
        $this->load->model('hotcity/hotcity_model');
        $this->load->model('buildings/buildings_model');
        $data['hot_city'] = $this->hotcity_model->hotCity();
        // 根据所有的cityID查询其楼盘数量
        if($data['hot_city']){
            foreach ($data['hot_city'] as $key => $value) {
               $data['hot_city'][$key]->buildingNum = $this->buildings_model->where("deleted = 0 and city_id = '$value->city_id' and publish = 1 ")->count_all();
            }
        }
        // 根据板块获取所有已开通的城市
        $citiestmp = $this->area_model->select("area_id,area_name,code,plates")->where('active=1 and deleted=0')->find_all();
        $area_block_name = area_block_name();
        foreach ($citiestmp as $key => $val) {
            $cities[$area_block_name[$val->plates]][] = $val;
        }
        $data['cities'] = $cities;
        // dump($data);exit();
        $this->load->view('front/plusfang/index', $data);
    }
    /**
     * [fangPlusList 列表页面]
     * @author [author]
     * @DateTime 2017-02-10T10:26:02+0800
     * @return   [type]                   [description]
     */
    public function fangPlusList($cityCode){
        if (empty($cityCode)) {
            // 默认调整到上海楼盘列表
            redirect($this->_listURL.'shanghai', 'auto', 302);
        }

        $get = $this->input->get();
        $page = isset($get['page']) ? $get['page'] : 1;
        $order = isset($get['order']) ? $get['order'] : null;
        $condition = isset($get['condition']) ? $get['condition'] : null;
        //今日头条渠道参数处理
        $buildingId = isset($get['id']) ? $get['id'] : '';
        // 区域
        $d = isset($get['d']) ? $get['d'] : null; 
        // 类型
        $t = isset($get['t']) ? $get['t'] : null;
        // 特色
        $tg = isset($get['tg']) ? $get['tg'] : null;
        // 价格
        $p = isset($get['p']) ? $get['p'] : null;
        // 加载模型
        $this->load->model('hometop/hometop_model');
        $this->load->model('hotcity/hotcity_model');
        $this->load->model('area/area_model');
        $this->load->model('buildings/buildings_model');
        $this->load->model('buildings/buildingsinfo_model');
        $this->load->model('buildings/buildingstag_model');
        $this->load->model('price/price_model');
        $this->load->library('user_agent');

        $limit = 5;
        // 根据板块获取所有已开通的城市
        $citiestmp = $this->area_model->select("area_id,area_name,code,plates")->where('active=1 and deleted=0')->find_all();
        $area_block_name = area_block_name();
        foreach ($citiestmp as $key => $val) {
            $cities[$area_block_name[$val->plates]][] = $val;
        }
        $data['cities'] = $cities;
        // 已选的筛选条件
        $queryArr = [];
        // 地区类型 0:country,1:province,2:city,3:district
        $city = $this->area_model->select('area_id,area_name,code')->find_by(['code'=>$cityCode, 'area_type'=>2, 'active'=>1]);
        if (!$city) redirect("/", 'auto', '302');
        $data['city'] = $city;
        $districtArr = $this->area_model->select('area_id,area_name as name')->where('parent_id', $city->area_id)->find_all();
        $url = $this->_listURL.$cityCode;
        $normalActive = 1;
        foreach ($districtArr as $key => $val) {
            $queryData['d'] = $val->area_id;
            $districtArr[$key]->url = "{$url}?".$this->query_data($queryData, $get);
            $districtArr[$key]->url_active = ($d == $val->area_id) ? 1 : 0;
            $districtArr[$key]->disabled = 0;
            if ($d == $val->area_id) {
                $normalActive = 0;
                $queryDistrict = $districtArr[$key];
                $queryDistrict->url = "{$url}?".$this->query_data(['d'=>''], $get);
                $queryArr['area'] = $queryDistrict;

                // $curOption['area'] =  $val->area_name;
            }
        }
        array_unshift($districtArr, (object)['name'=>'不限', 'url'=>"{$url}?".$this->query_data(['d'=>''], $get), 'url_active'=>$normalActive, 'disabled'=>0]);
        $data['districts'] = &$districtArr;
        // 热门楼盘
        // $hotBuildings = $this->buildings_model->select("id,name")->where("city_id = {$city->area_id}")->order_by("rand()")->limit(2)->find_all();
        $hotBuildings = $this->buildings_model->select("id,name")->where("city_id = {$city->area_id}")->limit(2)->find_all();
        $data['hot_buildings'] = $hotBuildings;
        // 楼盘类型
        $buildingType = building_room_type();
        $queryData = [];
        $normalActive = 1;
        foreach ($buildingType as $key => $val) {
            $queryData['t'] = $key;
            $type = (object)['url'=>"{$url}?".$this->query_data($queryData, $get), 
                                'name'=>$val, 
                                'url_active'=>($t == $key) ? 1 : 0];
            $buildingType[$key] = $type;
            if ($t == $key) {
                $normalActive = 0;
                $queryBuildingType = $buildingType[$key];
                $queryBuildingType->url = "{$url}?".$this->query_data(['t'=>''], $get);
                $queryArr['type'] = $queryBuildingType;
            }
        }
        array_unshift($buildingType, (object)['name'=>'不限', 'url'=>"{$url}?".$this->query_data(['t'=>''], $get), 'url_active'=>$normalActive]);
        $data['building_type'] = $buildingType;
        // 城市价格
        $cityPrice = $this->price_model->select('price,price_digit,city_id')->where("city_id = {$city->area_id} AND deleted = 0")->find_all();
        $queryData = [];
        $priceWhere = '';
        $normalActive = 1;
        foreach ($cityPrice as $key => $val) {
            $pVal = 'p'.($key+1);
            $priceExplode = explode('-', $val->price_digit);
            $val->where = "ave_price >= {$priceExplode[0]} AND ave_price < {$priceExplode[1]}";
            if (empty($priceExplode[0])) {
                $val->where = "ave_price < {$priceExplode[1]}";
            } else if (empty($priceExplode[1])) {
                $val->where = "ave_price > {$priceExplode[0]}";
            }
            $queryData['p'] = $pVal;//$val->val;
            $cityPrice[$key]->name = $val->price;
            $cityPrice[$key]->url = "{$url}?".$this->query_data($queryData, $get);
            $cityPrice[$key]->url_active = ($p == $pVal) ? 1 : 0;
            // 价格条件
            if ($p == $pVal) {
                $normalActive = 0;
                $priceWhere = " AND {$val->where}";
                $queryPrice = $cityPrice[$key];
                $queryPrice->url = "{$url}?".$this->query_data(['p'=>''], $get);
                $queryArr['price'] = $queryPrice;
            }
        }

        array_unshift($cityPrice, (object)['name'=>'不限', 'url'=>"{$url}?".$this->query_data(['p'=>''], $get), 'url_active'=>$normalActive]);
        $data['city_price'] = $cityPrice;
        // 排序数据
        $orderActive = "active";
        $queryData = [];
        $aClass = '';
        $orderArr = [(object)['name'=>'默认', 'val'=>'o2', 'a_class'=>'active'],(object)['name'=>'价格', 'val'=>'o3',  'a_class'=>''], (object)['name'=>'开盘时间', 'val'=>'o1',  'a_class'=>'']];
        foreach ($orderArr as $key => $value) {
            $orderUrl = $value->val;
            if(isset($order)){
                if($order == $value->val){
                    $orderArr[$key]->a_class = $orderActive;
                }else{
                    $orderArr[$key]->a_class = "";
                }
            }
            $queryData['order'] = $orderUrl;
            $orderArr[$key]->url = "{$url}?".$this->query_data($queryData, $get);
            // if ($order == 'o2') {
            //     $orderArr[$key]->url = "{$url}?".$this->query_data(['order'=>''], $get);
            // }
        }
        $data['order_arr'] = $orderArr;
        $queryData['order'] = $order;

        // dump($data['order_arr']);exit();
        // 楼盘数据
        $where = "deleted = 0 AND publish = 1";
        // 区域条件
        $where .= $d == null ? " AND city_id = {$city->area_id}" : " AND district_id = {$d}";
        // 价格条件
        $where .= $priceWhere;

        $buildingTable = $this->buildings_model->get_table();
        $infoTable = $this->buildingsinfo_model->get_table();
        //头条数据
        if(!empty($buildingId) && $page == 1 ){
            $buildingByJrtt = $this->buildings_model->select("*")
                                                ->join($infoTable, "{$buildingTable}.id = {$infoTable}.building_id")
                                                ->find($buildingId);
            if( $buildingByJrtt ){ $where .= " and {$buildingTable}.`id` != {$buildingId}"; }
        }
        $orderBy = $this->order_by($order) ? : ["{$buildingTable}.`id`"=> "DESC"];
        $buildings = $this->buildings_model->select("*")
                                            ->where($where)
                                            ->join($infoTable, "{$buildingTable}.id = {$infoTable}.building_id")
                                            ->limit($limit, ($page-1)*$limit)
                                            ->order_by($orderBy)
                                            ->find_all();
        //将头条指定数据插入数组第一个
        if( isset($buildingByJrtt) && !empty($buildingByJrtt) ){
            if (!is_array($buildings)) $buildings = [];
            array_unshift( $buildings, $buildingByJrtt);
        }                                 
        if ($buildings) {
            foreach ($buildings as $key => $val) {
                $tags = $this->buildingstag_model->tags($val->building_id);
                if ($val->price_desc != '') {
                    $price = $val->price_desc;
                    $number = preg_replace('/\D/s', '', $price);  
                    $buildings[$key]->price_desc = str_replace($number, "<span>¥".number_format($number)."</span>", $price);
                }
                $buildings[$key]->tags = isset($tags['putong']) ? $tags['putong'] : [];
                $district = $this->area_model->select('area_id,area_name')->find($val->district_id);
                $buildings[$key]->district = $district;
                $photos = $this->buildings_model->getBuildingPhotos($val->building_id);
                $buildings[$key]->cover = $photos['cover']['pc'][0];
                $buildings[$key]->ave_price = number_format($val->ave_price);
                // foreach ($districtArr as $k => $v) {
                //     if (isset($v->area_id) && ($val->district_id == $v->area_id)) $districtArr[$k]->disabled = 0;
                // }
            }
        }
        $data['buildings'] = $buildings;
        $currentQuery = $this->current_url_query($get);
        $data['current_query'] = $currentQuery;
        // dump($buildings);
        // 分页
        $currentUrl = "{$url}?".$currentQuery;
        $totalRows = $this->buildings_model->select("*")->where($where)->count_all();
        $this->load->library('pagination');
        $this->pager['base_url']    = $currentUrl;
        $this->pager['total_rows']  = $totalRows;
        $this->pager['per_page']    = $limit;
        $this->pager['use_page_numbers'] = true;
        $this->pager['page_query_string'] = true;
        $this->pager['enable_query_strings'] = true;
        $this->pager['query_string_segment'] = 'page';
        $this->pagination->initialize($this->pager);
        // echo $this->pagination->create_links();

        $data['query_arr'] = $queryArr;
        $data['city_code'] = $cityCode;
        $data['list_url'] = $url;
        $data['qd'] = isset($get['qd']) ? $get['qd'] : '';
        $data['listurl'] = $this->_listURL;

        // dump($data['city']);exit();
        $this->load->model('channel/channel_model');
        $channel = $data['qd'];
        $hasChannel = $this->channel_model->count_by('code', $channel);
        $data['show_qyyx58'] = ($this->agent->is_mobile() && !in_array($channel, ['baidu', 'bd1', 'bd', 'bdka', 'other']) && $hasChannel) ? 1 : 0;
        $ms = date("Hi");
        if ($this->agent->is_mobile() 
            && in_array($channel, ['baidu', 'bd1', 'bd']) 
            && (($ms >= 1830 && $ms <= 2359) || ($ms >= 0 && $ms <= 0859) || in_array(date("N"), [6,7]))) {
            // 这个条件下百度相关渠道
            $data['show_qyyx58'] = 1;
        }

        // dump($data);exit();
        // 加载视图
        if ($condition) {
            $this->load->view('front/building/condition', $data);
        } else {
            $this->load->view('front/plusfang/list', $data);
        }
    }
        /**
     * 楼盘数据排序规则
     * @param  string $order key
     * @return mixed
     * @author zephan <zephanliu@gmail.com>
     */
    private function order_by($order) {
        $orderBy['o1'] = ['open_time'=>'ASC'];
        $orderBy['o2'] = ['open_time'=>'DESC'];
        $orderBy['o3'] = ['ave_price'=>'ASC'];
        $orderBy['o4'] = ['ave_price'=>'DESC'];
        return isset($orderBy[$order]) ? $orderBy[$order] : '';
    }

    /**
     * 楼盘当前页面的筛选参数
     * @param  array $get get
     * @return string
     * @author zephan <zephanliu@gmail.com>
     */
    private function current_url_query($get) {
        $queryData = [];
        if (isset($get['d'])) {
            $queryData['d'] = $get['d'];
        }
        if (isset($get['t'])) {
            $queryData['t'] = $get['t'];
        }
        if (isset($get['tg'])) {
            $queryData['tg'] = $get['tg'];
        }
        if (isset($get['p'])) {
            $queryData['p'] = $get['p'];
        }
        if (isset($get['order'])) {
            $queryData['order'] = $get['order'];
        }
        if (isset($get['id'])) {
            $queryData['id'] = $get['id'];
        }
        if (isset($get['qd'])) {
            $queryData['qd'] = $get['qd'];
        }
        return http_build_query($queryData);
    }

    /**
     * 生成对应的url
     * @param  array $queryData
     * @param  array $get       get
     * @return string
     * @author zephan <zephanliu@gmail.com>
     */
    private function query_data($queryData, $get) {
        if (isset($get['d']) && !isset($queryData['d'])) {
            $queryData['d'] = $get['d'];
        }
        if (isset($get['t']) && !isset($queryData['t'])) {
            $queryData['t'] = $get['t'];
        }
        if (isset($get['tg']) && !isset($queryData['tg'])) {
            $queryData['tg'] = $get['tg'];
        }
        if (isset($get['p']) && !isset($queryData['p'])) {
            $queryData['p'] = $get['p'];
        }
        if (isset($get['order']) && !isset($queryData['order'])) {
            $queryData['order'] = $get['order'];
        }

        if (isset($queryData['d']) && $queryData['d'] == null) unset($queryData['d']);
        if (isset($queryData['t']) && $queryData['t'] == null) unset($queryData['t']);
        if (isset($queryData['tg']) && $queryData['tg'] == null) unset($queryData['tg']);
        if (isset($queryData['p']) && $queryData['p'] == null) unset($queryData['p']);
        if (isset($queryData['order']) && $queryData['order'] == null) unset($queryData['order']);

        return http_build_query($queryData);
    }
    /**
     * [search fangPlus搜索处理]
     * @author [author]
     * @DateTime 2017-02-13T15:28:53+0800
     * @return   [type]                   [description]
     */
    public function searchFang(){

        $get = $this->input->get();
        if(!empty($get['keyword'])){
            $this->load->model('buildings/buildings_model');
            $this->load->model('buildings/buildingsinfo_model');
            $buildingTable = $this->buildings_model->get_table();
            $infoTable = $this->buildingsinfo_model->get_table();
            
            $keyword = $this->repalce_str($get['keyword']);
            $city_id = $get['city_id'];
            if($city_id == 'all'){
                $where = "deleted = 0 and (name like '%".$keyword."%' or address like '%".$keyword."%')";
            }else{
                $where = "deleted = 0 and city_id = {$city_id} and (name like '%".$keyword."%' or address like '%".$keyword."%')";
            }
            $building = $this->buildings_model->select("*")
                                            ->where($where)
                                            ->join($infoTable, "{$buildingTable}.id = {$infoTable}.building_id")
                                            ->find_all();
            if($building){
                foreach ($building as $key => $value) {
                    //$building[$key]->info = $this->buildingsinfo_model->getInfoByBuildingId($value->id);
                    $temp = str_replace($keyword, "<span class='orange'>".$keyword."</span>", $value->name);
                    $building[$key]->name = $temp;
                    $tmp = str_replace($keyword, "<span class='orange'>".$keyword."</span>", $value->address);
                    $building[$key]->address_show = $tmp;
                    $building[$key]->city_info = $this->area_model->find($value->city_id);
                }
                if(!empty($building)){
                    echo json_encode($building);exit();
                }
            }else{  
                echo json_encode(2);exit();
            }   
            
        }
        
    }
    /**
     * 过滤特殊字符
     */
    private function repalce_str($str)
    {
        return str_replace(array("'",'"','>','<',"\\"),array('','','','',''),$str);
    }

    public function about() {
        if (is_fang90_server_name()) redirect(config_item('fang90.domain'));
        redirect("/", 'auto', '302');
        $this->load->view('front/home/about');
    }

    public function privacy() {
        if (is_fang90_server_name()) redirect(config_item('fang90.domain'));
        redirect("/", 'auto', '302');
        $this->load->view('front/home/privacy');
    }
    //首页楼盘切换选项
    public function ajaxLookBuild(){
            $this->load->model('tags/tags_model');
            $this->load->model('buildings/buildingstag_model');
            $this->load->model('buildings/buildings_model');
            $this->load->model('buildings/photos_model');
            $data['start'] = $start = 0;
            $data['offset'] = $offset = 10;
            // if($_GET){
                $get = $this->input->get();
                $code = $get['code'];
                if($code){
                    //根据code 获取到tag_id
                    $whereArray = array(
                        'url_str'=>$code,
                        'is_category'=>1,
                        );
                    $tags = $this->tags_model->find_by($whereArray);
                    // 读取目标分类楼盘数据
                    $targetBuildingIds = $this->buildingstag_model->limit($offset,$start)->where("tag_id = {$tags->tag_id} and type = 3")->order_by('building_id', 'DESC')->find_all();
                        foreach ($targetBuildingIds as $key => $value) {
                            $building_id = $value->building_id;
                            $tmp = $this->buildings_model->where("deleted = 0 ")->find($building_id);
                            if(!empty($tmp)){
                                $tmp->photo = $this->photos_model->getCoverPhotoByBuildingId($building_id);
                                 $citywhere = array(
                                        'area_id'=>$tmp->city_id
                                    );
                                 $city = $this->area_model->find_by($citywhere);
                                 $tmp->city_code = $city->code;
//                               $tmp->brower = $this->cache->redis->get("brower_index_".$value->building_id)+$this->init_num;
                                 $buildings[] = $tmp;
                            }
                        }
                        $str="";
                        if($buildings){
                            foreach ($buildings as $key => $value){
                                $price = $value->ave_price == 0 ? '待定' : $value->ave_price.'元/平米';
                                $str  .=  '<li class="building-grid-block jxlp_p">';
                                $str  .=  '<a href="/building/'.$value->city_code.'/'.$value->id.'/campaign">';
                                $str  .=  '<img src="'. $value->photo->absolute_url.'">';
                                $str  .=  '<p class="name">'.$value->name.'</p>';
                                $str  .=  ' <p class="price">'.$price.'</p>';
                                $str  .=  ' <p class="number">'.$value->brower.'次浏览</p>';
                                $str  .=  '</a>';
                                $str  .=  '</li>';
                            }
                        }
                        echo $str;
                }
            // }
    }
    /**
      * 读取配置文件
      * 
      */
    private function getConf($confname) {
        $file = $confname.'.php';
        return require_once($file);
    }
    /**
      * 加载更多
      * 
      */
    public function ajaxLoadMore(){
        $this->load->model('tags/tags_model'); 
        $this->load->model('buildings/buildingstag_model');
        $this->load->model('buildings/buildings_model');
        $this->load->model('buildings/photos_model');

        $get = $this->input->get();
        $category = $get['code'];
        $data['startNum'] = $start = $get['startNum'];
        $data['offset'] = $offset = 8;
        $cityId = $get['citycode'];
        if($category){
            //根据code 获取到tag_id
            $whereArray = array(
                        'url_str'=>$category,
                        'is_category'=>1,
                );
            $tags = $this->tags_model->find_by($whereArray);
            // 读取所有精选楼盘（tag_id = 2）的数据（type  1普通标签 2特色标签 3分类标签 4楼盘类型(住宅|别墅) 5装修情况）
            $targetBuildingIds = $this->buildingstag_model->limit($offset,$start)->where("tag_id = {$tags->tag_id} and type = 3")->order_by('building_id', 'DESC')->find_all();
            
            if($targetBuildingIds){
                $b_where = "deleted = 0 ";
                if(isset($cityId) && !empty($cityId)){
                    $b_where .= " and city_id = {$cityId}";
                }
                foreach ($targetBuildingIds as $key => $value) {
                        $tmp = $this->buildings_model->where($b_where)->find($value->building_id);
                        if(!empty($tmp)){
                            $tmp->photo = $this->photos_model->getCoverPhotoByBuildingId($value->building_id);
                            $citywhere = array(
                                        'area_id'=>$tmp->city_id
                                    );
                             $city = $this->area_model->find_by($citywhere);
                             $tmp->city_code = $city->code;
//                           $tmp->brower = $this->cache->redis->get("brower_index_".$value->building_id)+$this->init_num;
                             $tmp->tags = $this->buildingstag_model->tags($value->building_id);
                             $buildings[] = $tmp;
                        }
                }
            $str="";
            if($buildings){
                    $data['loadNums'] = count($buildings);
                    $data['startNum'] = $start+$offset;
                    foreach ($buildings as $key => $value){
                        if($value->id == '1649'){
                            $price = "980万起";
                        }else{
                            $price = $value->ave_price == 0 ? '待定' : $value->ave_price.'元/平米'.(($value->id == '1627') ? "起" : '');
                        }                             
                        $str  .=  '<li class="building-grid-block">';
                        $str  .=  '<a href="/building/'.$value->city_code.'/'.$value->id.'/campaign">';
                        $str  .=  '<img src="'. $value->photo->absolute_url.'">';
                        $str  .=  '<p class="name">'.$value->name.'</p>';
                        $str  .=  '<p class="price">'.$price.'</p>';
                        $str  .=  '<p class="number">';
                        if ($value->tags) {
                            foreach ($value->tags['putong'] as $ptTag) {
                                $str .= '<span>'.$ptTag->tag_name.'</span>';
                            }
                        }
                        $str  .=  '</p>';
                        $str  .=  '</a>';
                        $str  .=  '</li>';
                    }
            }
                $data['str'] = $str;
                echo json_encode($data);die();
            }else{
                $data = "noMore";
                echo json_encode($data);die();
            }
         }
    }

    /**
    *新闻详情页
    */
    public function newsdetail(){
        $id = $this->uri->segment(3);
        //dump($id);exit();
        //楼盘动态
        $new_records = $this->news_model->find($id);
        if($new_records){
                if($new_records->type == 2){
                    redirect('/', 'auto', 301);
                }
                $new_records->tags = $this->newstag_model->tags($new_records->id);
                //获取分类
                if(isset($new_records->tags['tese'])){
                    $newcategory="";
                    foreach ($new_records->tags['tese'] as $fkey => $fvalue) {
                        
                            $newcategory .= $fvalue->tag_name."、";
                        }
                            $str_category = substr($newcategory, 0, -3);
                            $new_records->fenlei = $str_category;

                }else{
                        $new_records->fenlei = "无";
                }
                //获取标签
                if(isset($new_records->tags['putong'])){
                    $newtag="";
                    foreach ($new_records->tags['putong'] as $tkey => $tvalue) {
                        
                            $newtag[] = $tvalue->tag_name;
                        }
                            //$str_tag = substr($newtag, 0, -3);
                            $new_records->tags = $newtag;
                    }else{
                        $new_records->tags = "无";
                    }
            }
        if(!empty($new_records->publish_time)){
            $new_records->ptime = $this->getTime($new_records->publish_time);
        }else{
            $new_records->ptime = $this->getTime($new_records->ctime);
        }
        
        $new_records->whole_url = site_url($new_records->url);
        $data['new_records'] = $new_records;
        //取最新的3条新闻
        $recommend_records = $this->news_model->where("id !=".$id." and status=2 and type = 1")->order_by("ctime","DESC")->limit(3,0)->find_all();
        if($recommend_records){
            foreach ($recommend_records as $key => $value) {
                // 城市参数
                $city_id = !empty($value->city)?$value->city:"321";
                $citycode = $this->area_model->find($city_id);
               $recommend_records[$key]->whole_url = site_url("news/".$citycode->code."/".$value->id);

            }
        //dump($recommend_records);exit();
        $data['recommend_records'] = $recommend_records;
        }


        $this->load->view('front/home/news', $data);

    }
    //推广文详情页
    public function postdetail(){
        $this->load->model('post/campaignphoto_model');
        $this->load->model('phone/phone_model');
        $this->load->model('channel/channel_model');
        $this->load->library('user_agent');
        $id = $this->uri->segment(2);
        $channel_name = $this->input->get('qd');
        // 4617888此链接强行先审核 只能单独处理
        $id = ($id == 4617888) ? 4617890 : $id;
        if($id == 4617888){
            //初始化微信sdk
            $options = [
                'app_id' => config_item("wechat.app_id"),
                'secret' => config_item("wechat.app_secret"),
            ];
            $app = new Application($options);
            $js = $app->js;
            $data['js'] = $js;
            $this->load->view('front/home/jd2', $data);
        }else{
            $new_records = $this->news_model->find($id);
            if($new_records){
                if($new_records->type == 1){
                    redirect('/', 'auto', 301);
                }
                $new_records->tags = $this->newstag_model->tags($new_records->id);
                //获取分类
                if(isset($new_records->tags['tese'])){
                    $newcategory="";
                    foreach ($new_records->tags['tese'] as $fkey => $fvalue) {

                        $newcategory .= $fvalue->tag_name."、";
                    }
                    $str_category = substr($newcategory, 0, -3);
                    $new_records->fenlei = $str_category;

                }else{
                    $new_records->fenlei = "无";
                }
                //获取标签
                if(isset($new_records->tags['putong'])){
                    $newtag="";
                    foreach ($new_records->tags['putong'] as $tkey => $tvalue) {

                        $newtag[] = $tvalue->tag_name;
                    }
                    //$str_tag = substr($newtag, 0, -3);
                    $new_records->tags = $newtag;
                }else{
                    $new_records->tags = "无";
                }
            }
            if(!empty($new_records->publish_time)){
                $new_records->ptime = $this->getTime($new_records->publish_time);
            }else{
                $new_records->ptime = "草稿";
            }
            if($new_records->campaign_mode == 2){

                $new_records->pic_array_mobile = $this->campaignphoto_model->where("new_id = ". $id." and platform = 2")->find_all();
            }
            $new_records->whole_url = site_url(!empty($new_records->url) ? $new_records->url : "无");
            $new_records->qd = !empty($channel_name) ? $channel_name : 'jrtt';
            if(empty($new_records->phone)){
                //获取分机号
                $channel_info = $this->channel_model->getChannelByCode($channel_name);
                $code = $this->input->get('code');
                if($code && $channel_name){
                    $ext_where = array(
                        'building_code'=>$code,
                        'channel_id'=>$channel_info->id,
                        'deleted'=>0
                    );
                }else{
                    $ext_where = array(
                        'building_code'=>$code,
                        'channel_id'=>13,
                        'deleted'=>0
                    );
                }
                $ext_arr = $this->phone_model->find_all_by($ext_where);
                if(!empty($ext_arr)){
                    foreach ($ext_arr as $key => $value) {
                        if($value->platform == 2){
                            $new_records->phone_ext = $value->number;
                        }else{
                            $new_records->pc_phone_ext = $value->number;
                        }
                    }
                }
            }else{
                //兼容修改之前的分机号数据
                $explode = explode(',', $new_records->phone);
                $new_records->phone_ext = count($explode)==2 ? $explode[1] : $explode[0];
            }
            //调取微信分享接口
            $this->load->library('wechatshare');
            $signPackage = $this->wechatshare->GetSignPackage();
            $data['signPackage'] = $signPackage;

            $data['ip_address'] = $this->ip_address;
            $data['is_mobile'] = $this->agent->is_mobile();
            $data['is_pad'] = stripos($this->agent->mobile, 'pad') === false ? 0 : 1;
            $data['new_records'] = $new_records;
            //dump($data['new_records']);exit();
            $this->load->view('front/home/post', $data);
        }
    }
    //发布时间显示规则
    private function getTime($time){ 
        $time = strtotime($time);
        if($time){
            $rtime = date("m-d H:i",$time);
            $htime = date("H:i",$time);
            $time = time() - $time;
                if ($time < 60)
                {
                    $str = '刚刚 ';
                }
                elseif ($time < 60 * 60)
                {
                    $min = floor($time/60);
                    $str = $min.'分钟前';
                }
                elseif ($time < 60 * 60 * 24)
                {
                    $h = floor($time/(60*60));
                    $str = $h.'小时前  ';
                }
                elseif ($time < 60 * 60 * 24 * 3)
                {
                    $d = floor($time/(60*60*24));
                    if($d==1)
                        $str = '昨天  ';
                    else
                        $str = '前天  ';
                }
                else
                {
                    $str = $rtime;
                }
                return $str;
         }
    } 
    /**
     * [topicDetail 专题页详情]
     * @author [fengchen@usuretech.com]
     * @DateTime 2016-12-28T10:07:05+0800
     * @return   [type]                   [description]
     */
    public function topicDetail(){

        $this->load->model('topic/topic_model');
        $this->load->model('area/area_model');

        $id = $this->uri->segment(2);
        $data = $this->topic_model->find($id);
        if($data){
            $cityArr = $this->area_model->find($data->city);
            $data->cityname = $cityArr->area_name;
            // $data->content = str_replace('topic/201612/', config_item('photo.domain').'topic/201612/', $data->content);
        }
        // 调取微信分享接口
        $this->load->library('wechatshare');
        $signPackage = $this->wechatshare->GetSignPackage();
        $result['signPackage'] = $signPackage;
        
        $result['data'] = $data;
        $this->load->view('front/home/topic', $result);
    }
    /**
     * [微信分享测试]
     * @author [author]
     * @DateTime 2017-02-21T10:48:23+0800
     * @return   [type]                   [description]
     */
    public function topicTest(){

        $id = $this->uri->segment(2);
        // echo $id;exit();
        $this->oauth($id);
        $wechatUserObj = $this->session->userdata($this->_sessionUserKey);
        // 构造分享的url
        $openid = $wechatUserObj['id'];
        $shareUrl =  "http://".$_SERVER['HTTP_HOST'].'/'.$this->_urlMiddle.'/'.$id."/".$openid;
        $this->load->model('topic/topic_model');
        $this->load->model('area/area_model');


        $data = $this->topic_model->find($id);
        if($data){
            $cityArr = $this->area_model->find($data->city);
            $data->cityname = $cityArr->area_name;
            $data->linkto = $shareUrl;
            // $data->content = str_replace('topic/201612/', config_item('photo.domain').'topic/201612/', $data->content);
        }
        // 调取微信分享接口
        $this->load->library('wechatshare');
        $signPackage = $this->wechatshare->GetSignPackage();
        $result['signPackage'] = $signPackage;
        // $config = [
        //     'app_id' => config_item("wechat.app_id"),
        //     'secret' => config_item("wechat.app_secret"),
        // ];
        // $app = new Application($config);
        // $result['js'] = $app->js;
        // $result['js'] = $js->config(array('onMenuShareAppMessage', 'onMenuShareTimeline', 'onMenuShareQQ'), true);
        $result['data'] = $data;
        // dump($result);exit();
        $this->load->view('front/home/topictest', $result);
    }
    /**
     * 微信登录验证
     * @param  string $action 回调的action
     * @return void         
     * @author zephan <zephanliu@gmail.com>
     */
    private function oauth($action) {
        // 未登录
        if (!$this->session->has_userdata($this->_sessionUserKey)) {
            $config = [
                'app_id' => config_item("wechat.app_id"),
                'oauth' => [
                    'scopes'   => ['snsapi_userinfo'],
                    'callback' => '/'.$this->_urlMiddle.'/wechatOauthBack',
                ],
            ];
            $app = new Application($config);
            $oauth = $app->oauth;

            $this->session->set_userdata('target_url', '/'.$this->_urlMiddle.'/'.$action);
            $oauth->redirect()->send();
        }
    }

    /**
     * 微信登录验证回调
     * @return void
     * @author zephan <zephanliu@gmail.com>
     */
    public function wechatOauthBack() {
        $config = [
            'app_id' => config_item("wechat.app_id"),
            'secret' => config_item("wechat.app_secret"),
        ];
        $app = new Application($config);
        $oauth = $app->oauth;
        // 获取 OAuth 授权结果用户信息
        $user = $oauth->user();
        $userArr = $user->toArray();
        $this->session->set_userdata($this->_sessionUserKey, $userArr);
        $targetUrl = empty($this->session->userdata('target_url')) ? '/' : $this->session->userdata('target_url');
        $wechatUser = $app->user->get($userArr['id']);
        // $this->wechatusers_model->subscribe($wechatUser);
        redirect($targetUrl);
    }
    
    public function sessions() {
        // $this->session->unset_userdata('phone_code');
        dump($this->session->userdata());
        echo APPPATH.'cache/ci3_sessions';
    }

    public function pinxiaochina(){
        $result['data'] = [];
        // dump($result);exit();
        $this->load->view('front/home/pinxiao', $result);
    }

    public function contactpx() {

        $this->load->view('front/home/contact-px');
    }
    public function companypx() {

        $this->load->view('front/home/company-px');
    }
    public function productpx(){
        $this->load->view('front/home/product-px');
    }


}
